
# #############################################################################
# Documents package
#
# --
#    Author: David Aguilera
#       Created: 04/05/2011
# 
# #############################################################################

APP_NAME = "exsited"

import gtk
import os, os.path
import tempfile, shutil
import gettext
gettext.bindtextdomain(APP_NAME)
gettext.textdomain(APP_NAME)
_ = gettext.gettext

from datetime import datetime
from plasTeX.TeX import TeX

from ExsitedRenderer import Renderer

class Document():
   ast = None
   filename = None
   tmpdir = None
   dirty = True
   user_set_name = True

   def __init__(self, filename=None):
      self.filename = filename
      self.tmpdir = tempfile.mkdtemp(prefix="exsited-")

      if filename == None:
         self.load_template()
      else:
         self.open(filename)

   def load_template(self):
      pass

   def close(self):
      if self.dirty:
         if self.user_set_name:
            save_it_label = _("Save")
            name = self.filename
         else:
            save_it_label = _("Save As")
            name = _("Unsaved Document")

         title = _("Save changes to document \"%(name)s\" before closing?") % { 'name' : name }

         seconds = 60
         if seconds < 3600:
            minutes = seconds/60
            if minutes == 0:
               minutes = 1
            expl = gettext.ngettext(
               "If you don't save, changes from the last minute will be permanently lost.",
               "If you don't save, changes from the last %(time)d minutes will be permanently lost.",
               minutes
               ) % { 'time' : minutes }
         else:
            expl = _("If you don't save, changes from the last %(time)d hours will be permanently lost.") % { 'time' : seconds/3600 }

         md = gtk.MessageDialog(self.__get_exsited_window(),
            gtk.DIALOG_MODAL, gtk.MESSAGE_WARNING, gtk.BUTTONS_NONE, title)
         md.format_secondary_text(expl)
         md.add_button("Do not Save changes", gtk.RESPONSE_REJECT)
         md.add_button(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL)
         md.add_button(save_it_label, gtk.RESPONSE_ACCEPT)

         response = md.run()
         md.destroy()
         if response == gtk.RESPONSE_ACCEPT:
            return self.save()

         return response != gtk.RESPONSE_CANCEL

   def destroy(self):
      shutil.rmtree(self.tmpdir)

   def get_html_location(self):
      return self.tmpdir + "/file.html"

   def save(self):
      dest = self.filename
      if not self.user_set_name:
         dialog = gtk.FileChooserDialog("Save As...", self.__get_exsited_window(),
           gtk.FILE_CHOOSER_ACTION_SAVE, (
              gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_SAVE, gtk.RESPONSE_OK
           )  )

         response = dialog.run()
         if response == gtk.RESPONSE_OK:
            dest = dialog.get_filename()
            with open(dest, "w+") as fd: fd.write(self.get_tex_contents())
         dialog.destroy()
         return response == gtk.RESPONSE_OK

      with open(dest, "w+") as fd: fd.write(self.get_tex_contents())
      return True


   def open(self, filename):
      tex = TeX(file=filename)
      tex.ownerDocument.config["files"]["filename"] = self.get_html_location()
      self.ast = tex.parse()

      shutil.copytree("scripts", self.tmpdir + "/scripts")

      cwd = os.getcwd()
      os.chdir(self.tmpdir)

      r = Renderer()
      r.render(self.ast)

      os.chdir(cwd)

   def get_tex_contents(self):
      return "These are the contents"

   def __get_exsited_window(self):
      exsited = None
      for window in gtk.window_list_toplevels():
         if window.is_active():
            exsited = window


class Article(Document):

   def load_template(self):
      print "Loading template..."
      template = "defaults/article.tex"
      self.filename = "article.tex"
      self.user_set_name = False

      tmp = tempfile.NamedTemporaryFile(prefix="article-", suffix=".tex").name
  
      out = open(tmp, "a")
      for line in open(template):
         line = line.replace("$author$", _("Author"))
         line = line.replace("$title$", _("Title"))
         line = line.replace("$date$", datetime.now().strftime(_("%B %d, %Y")))
         line = line.replace("$abstract$", _("Write here your article's abstract."))
         line = line.replace("$section$", _("Introduction"))
         line = line.replace("$type$", _("Hello! You can start your article by typing here."))
         out.write(line)
      out.close()

      self.open(tmp)
      os.remove(tmp)

